package com.ohuang.jiaxiaotong.Activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.NinePatchDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.ohuang.jiaxiaotong.MyHttpURL;
import com.ohuang.jiaxiaotong.R;
import com.ohuang.jiaxiaotong.Util.Ohuang;
import com.ohuang.jiaxiaotong.Util.Sys;
import com.ohuang.jiaxiaotong.base.BaseAc;
import com.ohuang.jiaxiaotong.entity.EventMsg;
import com.ohuang.jiaxiaotong.entity.User;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

import cn.bingoogolapple.photopicker.util.BGAPhotoHelper;
import cn.bingoogolapple.photopicker.util.BGAPhotoPickerUtil;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

//上传用户头像
public class UploadIconActivity extends BaseAc implements EasyPermissions.PermissionCallbacks {
    private static final int REQUEST_CODE_PERMISSION_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PERMISSION_TAKE_PHOTO = 2;

    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_TAKE_PHOTO = 2;
    private static final int REQUEST_CODE_CROP = 3;
    private BGAPhotoHelper mPhotoHelper;
    private ImageView mAvatarIv, imageView;
    private OkHttpClient okHttpClient = new OkHttpClient();
    private String name = "tom";
    private static final int UPDATE_OK = 0, UPDATE_ERROR = 1, UPLOAD_ERROR = 2, NET_ERROR = 3;
    private User user;
    private Dialog dialogLoading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_icon);
        setTitle("头像上传");
        Ohuang.changeStatusBarTextImgColor(this, true);//设置手机状态栏字体为黑
        Objects.requireNonNull(getSupportActionBar()).setHomeAsUpIndicator(R.mipmap.icon_goback);//设置ActionBar返回按钮
        EventBus.getDefault().register(this);//注册EventBus

        mAvatarIv = findViewById(R.id.img_icon_upload);
        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");
        mPhotoHelper = new BGAPhotoHelper(takePhotoDir);


        if (user != null) {
            Glide.with(this).load(user.getUrl()).into(mAvatarIv);
        }

    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        BGAPhotoHelper.onSaveInstanceState(mPhotoHelper, outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        BGAPhotoHelper.onRestoreInstanceState(mPhotoHelper, savedInstanceState);
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_CHOOSE_PHOTO)
    public void choosePhoto() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            startActivityForResult(mPhotoHelper.getChooseSystemGalleryIntent(), REQUEST_CODE_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "请开起存储空间权限，以正常使用 Demo", REQUEST_CODE_PERMISSION_CHOOSE_PHOTO, perms);
        }
    }

    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_TAKE_PHOTO)
    public void takePhoto() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
        if (EasyPermissions.hasPermissions(this, perms)) {
            try {
                startActivityForResult(mPhotoHelper.getTakePhotoIntent(), REQUEST_CODE_TAKE_PHOTO);
            } catch (Exception e) {
                BGAPhotoPickerUtil.show(R.string.bga_pp_not_support_take_photo);
            }
        } else {
            EasyPermissions.requestPermissions(this, "请开起存储空间和相机权限，以正常使用 Demo", REQUEST_CODE_PERMISSION_TAKE_PHOTO, perms);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        System.out.println("resultCode:" + resultCode);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
                try {
                    startActivityForResult(mPhotoHelper.getCropIntent(mPhotoHelper.getFilePathFromUri(data.getData()), 200, 200), REQUEST_CODE_CROP);
                } catch (Exception e) {
                    mPhotoHelper.deleteCropFile();
                    BGAPhotoPickerUtil.show(R.string.bga_pp_not_support_crop);
                    e.printStackTrace();
                }
            } else if (requestCode == REQUEST_CODE_TAKE_PHOTO) {
                try {
                    startActivityForResult(mPhotoHelper.getCropIntent(mPhotoHelper.getCameraFilePath(), 200, 200), REQUEST_CODE_CROP);
                } catch (Exception e) {
                    mPhotoHelper.deleteCameraFile();
                    mPhotoHelper.deleteCropFile();
                    BGAPhotoPickerUtil.show(R.string.bga_pp_not_support_crop);
                    e.printStackTrace();
                }
            } else if (requestCode == REQUEST_CODE_CROP) {
//                BGAImage.display(mAvatarIv, R.mipmap.bga_pp_ic_holder_light, mPhotoHelper.getCropFilePath(), BGABaseAdapterUtil.dp2px(200));
                Glide.with(UploadIconActivity.this).load(mPhotoHelper.getCropFilePath()).into(mAvatarIv);

            }
        } else {
            if (requestCode == REQUEST_CODE_CROP) {
                mPhotoHelper.deleteCameraFile();
                mPhotoHelper.deleteCropFile();
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {

    }

    //上传按钮
    public void upLoadIconClick(View view) {
        if (Sys.isClick()) {
            if (user != null) {
                dialogLoading = Ohuang.dialogLoadingshow(this, "上传中");

                uploadImg();


            }
        }
    }

    //拍照按钮
    public void takePhotoClick(View view) {
        takePhoto();
    }

    //打开相册按钮
    public void openAlbumClick(View view) {
        choosePhoto();
    }

    //上传图片
    private void uploadImg() {
        Bitmap bitmap = drawableToBitmap(mAvatarIv.getDrawable());

        OkHttpClient client = new OkHttpClient();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] data = baos.toByteArray();

        final RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file", "1.png",
                        RequestBody.create(MediaType.parse("multipart/form-data"), data))
                .build();

        Request request = new Request.Builder()
//                .header("Authorization", "Client-ID " + UUID.randomUUID())
                .url(MyHttpURL.mainUrl + "user/upload")
                .post(requestBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(NET_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String responseCode = response.body().string();
                if ("error".equals(responseCode)) {//图片上传失败
                    handler.sendEmptyMessage(UPLOAD_ERROR);
                } else {//图片上传成功 开始更改头像
                    httpUpdateIcon(responseCode);
                }
            }
        });
    }

    //drawable转化为Bitmap
    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        } else if (drawable instanceof NinePatchDrawable) {
            Bitmap bitmap = Bitmap
                    .createBitmap(
                            drawable.getIntrinsicWidth(),
                            drawable.getIntrinsicHeight(),
                            drawable.getOpacity() != PixelFormat.OPAQUE ?
                                    Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
            Canvas canvas = new Canvas(bitmap);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            drawable.draw(canvas);
            return bitmap;
        } else {
            return null;
        }
    }

    //更换头像
    private void httpUpdateIcon(String IconUrl) {
        OkHttpClient client = new OkHttpClient();
        RequestBody formBody = new FormBody.Builder()
                .add("username", user.getUsername())
                .add("url", IconUrl)
                .build();

        final Request request = new Request.Builder()
                .url(MyHttpURL.mainUrl + "user/updatePhoto")
                .post(formBody)
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                handler.sendEmptyMessage(NET_ERROR);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                ResponseBody body = response.body();
                if (body != null) {
                    String code = body.string();
                    if ("success".equals(code)) {
                        handler.sendEmptyMessage(UPDATE_OK);
                    } else {
                        handler.sendEmptyMessage(UPDATE_ERROR);
                    }
                    body.close();
                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case UPDATE_OK://上传成功
                    dialogLoading.dismiss();
                    EventBus.getDefault().post(new EventMsg(0, "更新用户数据"));//头像已更新 通知MainActivity更新一下数据
                    Ohuang.dialogshow(UploadIconActivity.this, "上传成功"
                            , "头像已更新", new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    finish();
                                }
                            });
                    break;
                case UPDATE_ERROR:
                    dialogLoading.dismiss();
                    Toast.makeText(UploadIconActivity.this, "更新头像失败", Toast.LENGTH_SHORT).show();
                    break;
                case UPLOAD_ERROR:
                    dialogLoading.dismiss();
                    Toast.makeText(UploadIconActivity.this, "上传图片失败", Toast.LENGTH_SHORT).show();
                    break;
                case NET_ERROR:
                    dialogLoading.dismiss();
                    Toast.makeText(UploadIconActivity.this, "网络错误", Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    //eventBus获取User
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void GetUserEventBus(User user) {
        this.user = user;
        if (user != null && mAvatarIv != null) {
            Glide.with(this).load(user.getUrl()).into(mAvatarIv);
        }
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        if (item.getItemId() == android.R.id.home) {//左上角返回按钮
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
